import { Modal, Table, Form } from 'com';
import { Button } from 'antd';
import { getSubjects } from 'api/dictionary';
import { SearchAvailable } from 'api/teacher';
import { useEffect, useState, useMemo, useRef, useImperativeHandle, forwardRef } from 'react';
import menuStore from 'store/menu';

/**
 * 教师列表
 */
export default forwardRef((props, ref) => {
    const { onFinish, all, multi } = props;
    /**
     * 教师列表
     */
    const [list, setList] = useState([]);
    /**
     * 选中的数据列表
     */
    const [selectedRows, setSelectedRows] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 总条数
     */
    const [total, setTotal] = useState(0);
    /**
     * Modal引用
     */
    const modal = useRef();
    /**
     * 查询数据
     */
    const [searchModel, setSearchModel] = useState({
        subject: 0,
        pageNo: 1,
        pageSize: 10,
        all
    });
    /**
     * 所有选中的key
     */
    const keys = useMemo(() => selectedRows.map(c => c.id), [selectedRows]);
    /**
     * 科目列表
     */
    const [subjects, setSubjects] = useState([{ label: '所有', value: 0 }]);
    /**
     * 表单配置项
     */
    const options = useMemo(() => ({
        name: {
            title: '教师姓名',
            max: 20,
        },
        idNo: {
            title: '身份证号',
            max: 18,
        },
        phone: {
            title: '手机号',
            max: 11
        },
        subject: {
            tag: 'select',
            title: '科目',
            style: { minWidth: 100 },
            values: subjects
        },
        button: {
            tag: 'button',
            text: '搜索',
            loading,
            htmlType: 'submit'
        }
    }), [loading, subjects]);
    /**
     * 列定义
     */
    const cols = [{
        title: '用户名',
        dataIndex: 'username',
        align: 'center'
    },
    {
        title: '姓名',
        dataIndex: 'name',
        align: 'center'
    },
    {
        title: '性别',
        dataIndex: 'sex',
        align: 'center'
    },
    {
        title: '工号',
        dataIndex: 'work_no',
        align: 'center'
    },
    {
        title: '身份证号',
        dataIndex: 'idNo',
        align: 'center'
    },
    {
        title: '手机号',
        dataIndex: 'phone',
        align: 'center'
    },
    {
        title: '职称',
        dataIndex: 'position1',
        align: 'center'
    },
    {
        title: '科目',
        dataIndex: 'sub',
        align: 'center'
    },
    ...(multi ? [] : [{
        title: '操作',
        align: 'center',
        width: 80,
        render: (text, row) => <Button type="link" size="small" onClick={() => {
            onFinish({ ...row });
            modal.current.hide();
        }}>选择</Button>
    }])
    ];

    useEffect(() => {
        if (menuStore.auth('teacherList')) {
            /**
        * 搜索
        */
            const searchList = async () => {
                try {
                    setLoading(true);
                    const { data, total } = await SearchAvailable(searchModel);
                    setList(data);
                    setTotal(total);
                } catch (error) { }
                setLoading(false);
            }
            searchList();
        }
    }, [searchModel]);

    useEffect(() => {
        if (menuStore.auth('teacherList')) {
            const getList = async () => {
                try {
                    const list = await getSubjects();
                    setSubjects([{ label: '所有', value: 0 }, ...list.map(item => ({ label: item.name, value: item.id }))]);
                } catch (error) { }
            }
            getList();
        }
    }, []);

    useImperativeHandle(ref, () => ({
        ...modal.current
    }));

    /**
     * 选中值
     * @param {*} keys = [5]
     * @returns 
     */
    const onChange = keys => {
        const rows = [...selectedRows];
        //遍历教师列表，查看哪个数据不存在，不存在则从选中的数据列表中删除
        for (const item of list) {
            if (keys.includes(item.id)) {
                if (!rows.some(c => c.id === item.id)) {
                    rows.push(item);
                }
            }
            else {
                const index = rows.findIndex(c => c.id === item.id);
                index >= 0 && rows.splice(index, 1);
            }
        }
        setSelectedRows(rows);
    }

    return <Modal title="选择教师" width={1200} attrs={{ footer: multi ? undefined : null }} ref={modal} onOk={() => {
        onFinish(selectedRows);
        modal.current.hide();
    }}>
        {menuStore.auth('teacherList') && <Form values={searchModel} options={options} attrs={{ layout: 'inline' }} onFinish={value => setSearchModel({ ...searchModel, ...value, pageNo: 1 })}></Form>}
        <p></p>
        {menuStore.auth('teacherList') && <Table attrs={multi && { rowSelection: { selectedRowKeys: keys, onChange } }} cols={cols} data={list} loading={loading} page={searchModel} total={total} onChange={setSearchModel}></Table>}
    </Modal>
})